﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;
using DomusDotNet.Sbm.Client.WP7.Models;
using DomusDotNet.Sbm.Client.WP7.ViewModels;

namespace DomusDotNet.Sbm.Client.WP7.Services
{
    public class FakeBackend : IBackend
    {

        public void Send(ICommand command)
        {
            Invoke(command, command);
        }

        public void Send<TResponse>(IQuery<TResponse> query, Action<TResponse> reply)
        {
            Invoke(query, query, reply);
        }


        readonly IEnumerable<MethodInfo> methods = typeof(FakeBackend)
            .GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
            .Where(x => x.Name == "Handle");


        Random rnd = new Random();
        void Invoke(object request, params object[] args)
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(2000 + rnd.Next(0, 6) * 500); //emulating network

                var requestType = request.GetType();
                var handler = methods.Where(x => requestType.IsAssignableFrom(x.GetParameters().First().ParameterType)).FirstOrDefault();
                if (handler == null) throw new ArgumentOutOfRangeException("request", "Handler not found for the message " + request.ToString());

                handler.Invoke(this, args);
            });
        }



        BookViewModel[] dummyBooks = new[] {
                new BookViewModel{ Title ="Refactoring", ISBN="9783827322784", AuthorNames=new[]{"Martin Fowler"}},
                new BookViewModel{ Title ="Domain-Driven Design", ISBN="9780321125217", AuthorNames=new[]{"Eric Evans"}},
                new BookViewModel{ Title ="Agile Software Development, Principles, Patterns, and Practices", ISBN="9780135974445", AuthorNames=new[]{"Robert C. Martin"}},
                new BookViewModel{ Title ="Design Patterns", ISBN="9780201309539", AuthorNames=new[]{"Erich Gamma", "Richard Helm", "Ralph Johnson" , "John Vlissides"}}
            };

        void Handle(BooksByCategoryQuery query, Action<IEnumerable<BookViewModel>> reply)
        {
            reply(dummyBooks);
        }
        void Handle(BooksByLendStatusQuery query, Action<IEnumerable<BookViewModel>> reply)
        {
            reply(dummyBooks);
        }

        void Handle(AllCategoriesQuery query, Action<IEnumerable<string>> reply)
        {
            reply(new[] { "design", "programming", "C#", "VB", });
        }
    }
}
